using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using LinkPointTransaction;
using System.Collections.Specialized;
using System.Configuration;
using SiteManager;
using System.Text;
using System.Data.SqlClient;


/// <summary>
///    The page is designed and  developed to implement the functionality of Become
///    a feature doctor and it's complete implementation of your Pay Payment Gateway.
///    Author: Akash Saxena 
///    Date: 11 Sep 2007
/// </summary>
public partial class Doctor_NewFeaturedDoctor : System.Web.UI.Page
{
    /// <summary>
    /// Create object of manager and doctor Class Respectively
    /// </summary>
    Manager ObjManager = new Manager(true,"ConnectionString");
    Doctor ObjDoctor = new Doctor();
    localFunction drchk = new localFunction();

    #region Variable Declaration
    /// <summary>
    /// Declare Variables
/// </summary>
    protected string configfile;
    protected string keyfile;
    protected string host;
    protected int port;
    protected LinkPointTxn LPTxn;
    protected bool fLog = false;
    protected int logLvl = 0;
    protected string logFile = "";
    protected string baddrnum = "";
    protected string bzip = "";
    //protected string bCity = "";
    //protected string bState = "";
    protected string Name = "";
    protected string Email = "";
    protected string cardnumber = "";
    protected string expmonth = "";
    protected string expyear = "05";
    protected string total = "";
    //string strDate = "";
    protected string startdate = "";
    protected string periodicity = "";
    protected string installments = "";
    protected string pbthreshold = "";
    int iDoctorid = 0;
    string SpecialityName = "";
    string errorMessage = String.Empty;
    string filename = String.Empty;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
            WizardSubscription.FinishCompleteButtonText = "Complete Your Order";
            WizardSubscription.StartNextButtonText = "Continue";
            WizardSubscription.FinishPreviousButtonText = "Back";
            WizardSubscription.StepPreviousButtonText="Back";
            WizardSubscription.StepNextButtonText = "Continue";
            txtcardnumber.Attributes.Add("onkeypress", "return CheckCardNo(event)");

            //Check Doctor Login
            drchk.checkDoctorLogin(true);
            //drchk.checkDentistLogin(true);      

            if (Session["userID"].ToString() != "" && Session["userID"] != null)
            {
                iDoctorid = Convert.ToInt32(Session["userID"]);

            }
            if (CheckDoctorExist())
            {
                WizardSubscription.Visible = false;
                lblMessage.Text = "You are already featured Doctor";
            }

            if (!Page.IsPostBack)
            {
                //Fill dropdowns
                LoadCommonControls();
                GetDoctorDetails();
                YearDisplay();
                MonthDisplay();
            }

              SpecialityDropDownSelectedValue();

              //if (WizardSubscription.ActiveStepIndex == 1)
              //{
              //    //string errorMessage = String.Empty;
              //    //string filename = String.Empty;
              //    // upload the doctor's image
              //    if (fupl_photo.HasFile)
              //    {
              //        errorMessage = ObjManager.UpLoadFile(fupl_photo, Server.MapPath("../images/Dr_images/"), ".jpg|.bmp|.gif|.jpeg", 512000);
              //        if (errorMessage.Length > 0)
              //        {
              //            lblErrorMessage.Text = errorMessage;
              //           // WizardSubscription.MoveTo(WizardStep2);
              //        }
              //        else
              //            filename = fupl_photo.FileName;
              //        ViewState["sfilename"]=filename;
                      
              //    }
              //}
              
                #region -- code declared obsolete by Kajal --
              //if (WizardSubscription.ActiveStepIndex == 2)
              //{
              //    if (CheckDoctorExist())
              //    {
              //        //Parse form data
              //        ParseFormData();
              //        // process order
              //        ProcessOrder();


              //        //Status Page
              //        // Put user code to initialize the page here

              //        HttpBrowserCapabilities bc = Request.Browser;
              //        fIE5 = (bc.Browser == "IE" && bc.MajorVersion > 4);

              //        order = (string)Session["outXml"];
              //        resp = (string)Session["resp"];
              //        ParseResponse(resp);

              //        if (R_Approved == "APPROVED")
              //        {
              //            SaveDataAfterApproval();
              //        }

              //    }
              //    else
              //    {
              //        Response.Redirect(Session["strHttp"].ToString() + "doctor/doctorContent.aspx");
              //    }

              //} 
              #endregion

                if (WizardSubscription.ActiveStepIndex == 0)
                {
                    
                    if (rbSubscription.Text == "2")//Monthly
                        {
                            if (ddlFeaturedDocType.Text == "1")//Standard Featured Doctor
                                {
                                    txttotal.Text = "49";
                                }
                                if (ddlFeaturedDocType.Text == "2")//Enhanced Featured Doctor
                                {
                                    txttotal.Text = "99";
                                }
                                if (ddlFeaturedDocType.Text == "3")//Premium Featured Doctor
                                {
                                    txttotal.Text = "199";
                                }
                        }
                        else if (rbSubscription.Text == "3")
                            {
                                if (ddlFeaturedDocType.Text == "1")
                                    {
                                        txttotal.Text = "499";
                                    }
                                    if (ddlFeaturedDocType.Text == "2")
                                    {
                                        txttotal.Text = "999";
                                    }
                                    if (ddlFeaturedDocType.Text == "3")
                                    {
                                        txttotal.Text = "1999";
                                    }

                            }
                        else
                            {
                                     txttotal.Text="1";
                            }

                }

        GetDoctorDetails();
   

    }


    private void ProcessOrder()
    {

        #region -- Auto XML declared obsolete by Kajal Mandal ---
        //// create order            
        //LPOrderPart order = LPOrderFactory.createOrderPart("order");
        //// create a part we will use to build the order
        //LPOrderPart op = LPOrderFactory.createOrderPart();

        //// Build 'orderoptions'
        //op.put("ordertype", "SALE");
        //// add 'orderoptions to order
        //order.addPart("orderoptions", op);

        //// Build 'merchantinfo'
        //op.clear();
        //op.put("configfile", configfile);
        //// add 'merchantinfo to order
        //order.addPart("merchantinfo", op);

        //// Build 'billing'
        //// Required for AVS. If not provided, 
        //// transactions will downgrade.
        //op.clear();
        //op.put("zip", bzip);
        ////op.put("City", bCity);
        ////op.put("State", bState);
        //op.put("addrnum", baddrnum);
        //// add 'billing to order
        //order.addPart("billing", op);

        //// Build 'creditcard'
        //op.clear();
        //op.put("cardnumber", cardnumber);
        //op.put("cardexpmonth", expmonth);
        //op.put("cardexpyear", expyear);
        //// add 'creditcard to order
        //order.addPart("creditcard", op);

        //// Build 'payment'
        //op.clear();
        //op.put("chargetotal", total);
        //// add 'payment to order
        //order.addPart("payment", op);

        //// build 'periodic' part
        //op.clear();
        //op.put("action", "SUBMIT");
        //op.put("startdate", startdate);
        //op.put("periodicity", periodicity);
        //op.put("installments", installments);
        //op.put("threshold", pbthreshold);
        //// add 'periodic' to order
        //order.addPart("periodic", op);

        //// create transaction object	


        //// get outgoing XML from the 'order' object
        //string outXml = order.toXML(); 
        #endregion

        StringBuilder MyXML = new StringBuilder(string.Empty);
        MyXML.Append("<order>");

        MyXML.Append("<merchantinfo>");
        MyXML.Append("<configfile>1001162886</configfile>");
        MyXML.Append("</merchantinfo>");

        MyXML.Append("<orderoptions>");
        MyXML.Append("<ordertype>SALE</ordertype>");
        MyXML.Append("</orderoptions>");

        MyXML.Append("<payment>");
        MyXML.Append("<chargetotal>1</chargetotal>"); // $1 set for testing. It should be dynamically filled up.
        MyXML.Append("</payment>");

        MyXML.Append("<creditcard>");
        MyXML.Append("<cardnumber>4111111111111111</cardnumber>");  // CC Number hard coded; must be dynamically filled up.
        MyXML.Append("<cardexpmonth>03</cardexpmonth>");            // CC Exp. Details hardcoded; must be dynamically filled up.
        MyXML.Append("<cardexpyear>09</cardexpyear>");
        MyXML.Append("</creditcard>");

        MyXML.Append("<periodic>");        
        MyXML.Append("<action>SUBMIT</action>");
        MyXML.Append("<installments>99</installments>");            // Maximum installments = 99.
        MyXML.Append("<threshold>3</threshold>");                   // Number of retries.
        MyXML.Append("<startdate>immediate</startdate>");           // immediate = datetime.now; use future date in case of coupons
        MyXML.Append("<periodicity>monthly</periodicity>");         // Monthly(m1)/Yearly(y1). Hardcoded to (d1)
        MyXML.Append("</periodic>");

        MyXML.Append("</order>");

        string outXml = MyXML.ToString();

        MyXML = null;

        // Call LPTxn
        LPTxn = new LinkPointTxn();
        string resp = LPTxn.send(keyfile, host, port, outXml);

        //Store transaction data on Session and redirect
        Session["outXml"] = outXml;
        Session["resp"] = resp;

        LPTxn = null;
        return;
    }

    private void YearDisplay()
    {
        ddlYear.Items.Insert(0, "Year");
        for (int i = 2007; i < 2013; i++)
        {
            ddlYear.Items.Add(i.ToString());
        }
    }
    private void MonthDisplay()
    {
        DataTable tbMonth = new DataTable();
        tbMonth.Columns.Add(new DataColumn("MonthNo"));
        tbMonth.Columns.Add(new DataColumn("MonthName"));
        tbMonth.Rows.Add(new object[] { "01", "Jan" });
        tbMonth.Rows.Add(new object[] { "02", "Feb" });
        tbMonth.Rows.Add(new object[] { "03", "Mar" });
        tbMonth.Rows.Add(new object[] { "04", "Apr" });
        tbMonth.Rows.Add(new object[] { "05", "May" });
        tbMonth.Rows.Add(new object[] { "06", "Jun" });
        tbMonth.Rows.Add(new object[] { "07", "July" });
        tbMonth.Rows.Add(new object[] { "08", "Aug" });
        tbMonth.Rows.Add(new object[] { "09", "Sep" });
        tbMonth.Rows.Add(new object[] { "10", "Oct" });
        tbMonth.Rows.Add(new object[] { "11", "Nov" });
        tbMonth.Rows.Add(new object[] { "12", "Dec" });
        ddlMonth.DataSource = tbMonth;
        ddlMonth.DataValueField = "MonthNo";
        ddlMonth.DataTextField = "MonthName";
        ddlMonth.DataBind();
        ddlMonth.Items.Insert(0, "Month");
       
    }
    
    protected void ParseFormData()
    {
        bzip = txtbzip.Text;
        //bState = txtState.Text.Trim().ToString();
        //bCity = txtCity.Text.Trim().ToString();
        baddrnum = txtbaddrnum.Text;
        cardnumber = txtcardnumber.Text;
        expmonth =  ddlMonth.SelectedValue.ToString();
        string r = ddlYear.SelectedValue.ToString();
        r = r.Substring(2);
        expyear = r;
        total = txttotal.Text;
        Name = txtName.Text;
        Email = txtEmail.Text;
        if ((total == null) || total.Length < 1) { total = "0.0"; }
        pbthreshold = "3";
        //strDate = System.DateTime.Now.ToShortDateString();
        //startdate = DateTime.Parse(strDate).ToString("yyyyMMdd");
        startdate = "immediate";
        periodicity = rbSubscription.SelectedItem.ToString();
        installments = "99";
        GetConfigParams();
    }

    private void GetConfigParams()
    {
        // get some stuff from app config
        //NameValueCollection config1 = (NameValueCollection)ConfigurationSettings.GetConfig("LPAPP_Config/client"); commented at 131008 to fix
        NameValueCollection config1 = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("LPAPP_Config/client");


        configfile = config1["Configfile"];
        keyfile = config1["Keyfile"];
        host = config1["Host"];
        port = Int32.Parse(config1["Port"]);

        //NameValueCollection config = (NameValueCollection)ConfigurationSettings.GetConfig("LPAPP_Config/opts");  commented at 131008 to fix
        NameValueCollection config = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("LPAPP_Config/opts");

        try
        {
            fLog = bool.Parse(config["fLog"]);
        }
        catch (Exception) { }

        try
        {
            logLvl = Int32.Parse(config["logLvl"]);
        }
        catch (Exception) { }

        try
        {
            logFile = config["logFile"];
        }
        catch (Exception) { }

    }

    private void LoadCommonControls()
    {
        ObjManager.BindList("select id,name from tbl_speciality order by name", "name", "id", ddlSpeciality, "");
        ObjManager.BindList("select FeatureDocTypeId,FeatureDocType from  tbl_FeatureDocType", "FeatureDocType", "FeatureDocTypeId", ddlFeaturedDocType, "");
        ddlFeaturedDocType.Items.Insert(0, new ListItem("Select", "0"));

        rbSubscription.Items.Add(new ListItem("Monthly", "m"));
        rbSubscription.Items.Add(new ListItem("Annual", "a"));
        rbSubscription.Items[0].Selected = true;
        return;
    }

    //Status Page
    protected void ParseResponse(string rsp)
    {
        R_Time = ParseTag("r_time", rsp);
        R_Ref = ParseTag("r_ref", rsp);
        R_Approved = ParseTag("r_approved", rsp);
        R_Code = ParseTag("r_code", rsp);
        R_Authresr = ParseTag("r_authresronse", rsp);
        R_Error = ParseTag("r_error", rsp);
        R_OrderNum = ParseTag("r_ordernum", rsp);
        R_Message = ParseTag("r_message", rsp);
        R_Score = ParseTag("r_score", rsp);
        R_TDate = ParseTag("r_tdate", rsp);
        R_AVS = ParseTag("r_avs", rsp);
        R_Tax = ParseTag("r_tax", rsp);
        R_Shipping = ParseTag("r_shipping", rsp);
        R_FraudCode = ParseTag("r_fraudCode", rsp);
        R_ESD = ParseTag("esd", rsp);
    }


    protected string ParseTag(string tag, string rsp)
    {
        StringBuilder sb = new StringBuilder(256);
        sb.AppendFormat("<{0}>", tag);
        int len = sb.Length;
        int idxSt = -1, idxEnd = -1;
        if (-1 == (idxSt = rsp.IndexOf(sb.ToString())))
        { return ""; }
        idxSt += len;
        sb.Remove(0, len);
        sb.AppendFormat("</{0}>", tag);
        if (-1 == (idxEnd = rsp.IndexOf(sb.ToString(), idxSt)))
        { return ""; }
        return rsp.Substring(idxSt, idxEnd - idxSt);
    }

    protected string order;
    protected string resp;
    protected bool fIE5;
    protected string R_Time;
    protected string R_Ref;
    protected string R_Approved;
    protected string R_Code;
    protected string R_Authresr;
    protected string R_Error;
    protected string R_OrderNum;
    protected string R_Message;
    protected string R_Score;
    protected string R_TDate;
    protected string R_AVS;
    protected string R_FraudCode;
    protected string R_ESD;
    protected string R_Tax;
    protected string R_Shipping;

    //
   
    
    private void GetDoctorDetails()
    {        
        SqlDataReader objDataReader = ObjManager.ExecuteQuery("select (fname +' ' + Mname+ ' ' +Lname)as DoctorName,Email,(Address1 +' '+Address2)as Address,City,State,ZipCode  from tbl_doctors  where id=" + iDoctorid);
        if (objDataReader.HasRows)
        {
            objDataReader.Read();
            txtName.Text = objDataReader["DoctorName"].ToString();
            txtbaddrnum.Text = objDataReader["Address"].ToString();
            txtCity.Text = objDataReader["City"].ToString();
            txtState.Text = objDataReader["State"].ToString();
            txtbzip.Text = objDataReader["ZipCode"].ToString();
            txtEmail.Text = objDataReader["Email"].ToString();

        }
        objDataReader.Close();
        objDataReader.Dispose();
    }
    private void SpecialityDropDownSelectedValue()
    {         
         SqlDataReader objDataReader = ObjManager.ExecuteQuery("select tbl_speciality.Name,tbl_speciality.id,tbl_doctors.fName from tbl_doctors inner join tbl_speciality  on tbl_speciality.id =tbl_doctors.SpecialityID  and tbl_doctors.id=" + iDoctorid);

        if (objDataReader.HasRows)
        {
            objDataReader.Read();
            SpecialityName = objDataReader["id"].ToString();
            if (SpecialityName.Length.Equals(0))
            {
                return;
            }
            else
            {
                ddlSpeciality.SelectedValue = SpecialityName;
            }
        }
        objDataReader.Close();
        objDataReader.Dispose();
    }

    /// <summary>
    /// To check that the doctor has already subscribed or not.
    /// </summary>
    /// <returns>True if exists, otherwise False</returns>
    /// <author>Akash Saxena</author>
    /// <date>06 Oct 2007</date>
    /// <remarks>Checked OK</remarks>
    private bool CheckDoctorExist()
    {
        object DocID = ObjManager.ExecuteScalarQuery("select isnull(doctorid,0) from doctorsubscription where doctorid=" + Convert.ToInt32(Session["userID"]));

        if (Convert.ToString(DocID) == "0") return false;
        else return true;
    }

    private void SaveDataAfterApproval()
    {
        //Write Code to add the processed value in database
        ObjDoctor.DoctorId = iDoctorid;
        ObjDoctor.TransactionId = R_Ref;
        ObjDoctor.TransactionDate = R_Time;//need to confirm  which date should be add ?? R_Time or startdate.
        ObjDoctor.TransactionAmount = txttotal.Text.ToString();
        ObjDoctor.SubscriptionId = R_OrderNum;
        ObjDoctor.SubscriptionType = rbSubscription.SelectedItem.ToString();
        ObjDoctor.FeaturedocTypeId = Convert.ToInt32(ddlFeaturedDocType.Text);
        ObjDoctor.SpecialityId = Convert.ToInt32(ddlSpeciality.Text);
        ObjDoctor.photo = ViewState["sfilename"].ToString();
        ObjDoctor.prof_desc = txtDoctorStatement.Text.Trim().ToString();
        ObjDoctor.website = txtWebSite.Text.Trim().ToString();       
        ObjDoctor.InsertDoctorSubscription();
    }
    /// <summary>
    /// This Function is created for Checking Coupon Code  
    /// 1)is active or not ??
    /// 2)and For which Doctor/Dentist is Created for 
    /// 3) and It also checks that This Coupon weather already used  or not ??
    /// </summary>
    private bool CheckCouponCodeExist()
    {
       
            ObjDoctor.UserType = 1;
            ObjDoctor.LoginID = Convert.ToInt32(Session["userID"]);
            if (txtCouponCode.Text.ToString().Length.Equals(0))
                return true;
            ObjDoctor.CouponCode = txtCouponCode.Text.Trim().ToString();
      
       return ObjDoctor.CheckCouponCode();
    }


    protected void WizardSubscription_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        lblWS1Message.Text = string.Empty;
        lblErrorMessage.Text = string.Empty;
        switch (WizardSubscription.ActiveStepIndex)
        {
            case 0:


                if (CheckCouponCodeExist())
                {
                    //coupon discount
                }
                else
                {
                    lblWS1Message.Text = "Invalid Coupon Code";
                    e.Cancel = true;

                }
                break;
            case 1:

                // upload the doctor's image
                if (fupl_photo.HasFile)
                {
                    errorMessage = ObjManager.UpLoadFile(fupl_photo, Server.MapPath("../images/Dr_images/"), ".jpg|.bmp|.gif|.jpeg", 512000);
                    if (errorMessage.Length > 0)
                    {
                        lblErrorMessage.Text = errorMessage;
                        e.Cancel = true;
                    }
                    else
                    {
                        filename = fupl_photo.FileName;
                        ViewState["sfilename"] = filename;
                    }
                }
                break;
        }

    }

    /// <summary>
    /// Process payment. Send request to YourPay Gateway and fetch back response.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <author>Kajal Mandal</author>
    /// <date>06 Oct 2007</date>
    protected void WizardSubscription_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        //if (!CheckDoctorExist())
        //{
            //Parse form data - Provided by YourPay
            ParseFormData();
            // process order - Provided by YourPay
            ProcessOrder();

            HttpBrowserCapabilities bc = Request.Browser;
            fIE5 = (bc.Browser == "IE" && bc.MajorVersion > 4);

            order = (string)Session["outXml"];
            resp = (string)Session["resp"];
            ParseResponse(resp);

            if (R_Approved == "APPROVED")
            {
                SaveDataAfterApproval();
            }

        //}
        //else
        //{
        //    Response.Redirect(Session["strHttp"].ToString() + "doctor/doctorContent.aspx");
        //}
    }
}


